﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace WindowService
{
    public enum LogType
    {
        Trace = 0,
        Info = 2,
        Warning = 4,
        Error = 8,
    }

    public class Log
    {
        private static object ob = " ";
        public static string SavePath = Environment.CurrentDirectory;
        public static bool needTrace = false;
        /**
         * 写日志
         */
        public static void WriteLog(string message, LogType logType = LogType.Info)
        {
            //是否需要 trace log
            if (!needTrace && logType == LogType.Trace)
            {
                return;
            }
            lock (ob)
            {
                StreamWriter writer = null;
                string logDirPath = SavePath;
                string logFilePath = logDirPath + "\\" + System.DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                if (!Directory.Exists(logDirPath))
                {
                    Directory.CreateDirectory(logDirPath);
                }
                if (!File.Exists(logFilePath))
                {
                    writer = File.CreateText(logFilePath);
                }
                else
                {
                    writer = new StreamWriter(logFilePath, true);
                }
                writer.WriteLine(System.DateTime.Now.ToString("HH:mm:ss") + " " + logType + " " + Log.gb2312_utf8(message));
                Console.WriteLine(System.DateTime.Now.ToString("HH:mm:ss") + " " + logType + " " + Log.gb2312_utf8(message));
                writer.Close();
            }
        }

        /// <summary>
        /// UTF8转换成GB2312
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string utf8_gb2312(string text)
        {
            //声明字符集   
            System.Text.Encoding utf8, gb2312;
            //utf8   
            utf8 = System.Text.Encoding.GetEncoding("utf-8");
            //gb2312   
            gb2312 = System.Text.Encoding.GetEncoding("gb2312");
            byte[] utf;
            utf = utf8.GetBytes(text);
            utf = System.Text.Encoding.Convert(utf8, gb2312, utf);
            //返回转换后的字符   
            return gb2312.GetString(utf);
        }

        /// <summary>
        /// GB2312转换成UTF8
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string gb2312_utf8(string text)
        {
            //声明字符集   
            System.Text.Encoding utf8, gb2312;
            //gb2312   
            gb2312 = System.Text.Encoding.GetEncoding("gb2312");
            //utf8   
            utf8 = System.Text.Encoding.GetEncoding("utf-8");
            byte[] gb;
            gb = gb2312.GetBytes(text);
            gb = System.Text.Encoding.Convert(gb2312, utf8, gb);
            //返回转换后的字符   
            return utf8.GetString(gb);
        }
    }
}
